package gui.view;

import java.awt.Component;
import java.awt.Container;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JScrollPane;

import gui.parser.Attr;

public class ViewGroup extends View {
	private List<View> children = new ArrayList<>();
	protected JScrollPane layout;

	public ViewGroup(Attr attr) {
		super(attr);
		layout = new JScrollPane();
		layout.setLayout(null);
	}

	public void addChild(View child) {
		children.add(child);
		if (child instanceof ViewGroup)
			getLayout().add(child.getLayout());
		else
			getLayout().add(child.getView());
		child.setParent(this);
	}

	public List<View> getChildren() {
		return children;
	}

	@Override
	public void init() {
		super.init();
	}

	public void invilidate(boolean flushChildren) {
		invalidate();
		if (flushChildren)
			for (View v : getChildren()) {
				if (v instanceof ViewGroup) {
					((ViewGroup) v).invilidate(flushChildren);
				}
				v.invalidate();
			}
	}

	@Override
	public void invalidate() {
		super.invalidate();
		setBounds();
	}

	@Override
	protected void setBounds() {
		super.setBounds();
	}

	@Override
	public Container getLayout() {
		return layout;
	}

	@Override
	public Component getView() {
		return getLayout();
	}

	public View findViewById(int id) {
		View view = null;
		for (View v : getChildren()) {
			if (v.getId() == id)
				return v;
			if (v instanceof ViewGroup) {
				view = ((ViewGroup) v).findViewById(id);
			}
		}
		return view;
	}
}
